<template>
  <div
    class="login"
    :style="{
      '--current-color': theme,
    }"
  >
    <div class="login-container">
      <div class="login-logo">
        <div class="login-logo__img"></div>
        <div class="login-logo__title">{{ title }}</div>
      </div>
      <div class="login-lt">
        <div class="login-lt__title">{{ title }}</div>
<!--        <div class="login-lt__subtit">2.0全新上线，仅需29元即可拥有!</div>-->
<!--        <div class="login-lt__des">项目 、管理层均可使用</div>-->
<!--        <a class="login-lt__link">查看<i class="el-icon-arrow-right"></i></a>-->
      </div>
      <div v-if="isWeChat" class="login-rt" key="1">
        <div class="login-wechat">
          <div class="login-wechat__title">
            <svg-icon icon-class="wechat" />
            微信扫码
          </div>
          <div id="wechat_qrcode"></div>
          <div class="login-wechat__tip">
            <i class="el-icon-success"></i>
            扫码登录即表示您同意并遵守<a>用户协议</a>
          </div>
          <div class="login-back" @click="changeLoginType(false)">
            返回上一页
          </div>
        </div>
      </div>
      <div v-else class="login-rt" key="2">
<!--        <svg-icon-->
<!--          class="login-rt__qrcode"-->
<!--          icon-class="icon-login_qrcode"-->
<!--          @click="changeLoginType(true)"-->
<!--        />-->
        <div class="login-tab">
          <div
            class="login-tab__item"
            :class="[activeTab === 0 ? 'active' : '']"
            @click="handleTab(0)"
          >
            账号登录
          </div>
          <div
            class="login-tab__item"
            :class="[activeTab === 1 ? 'active' : '']"
            @click="handleTab(1)"
          >
            验证码登录
          </div>
        </div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          :style="{ marginBottom: activeTab === 0 ? '0px' : '8px' }"
          @keyup.enter.native="handleLogin"
        >
          <template v-if="activeTab === 0">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="请输入用户名"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="请输入密码"
                show-password
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaEnabled">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
              >
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img" />
              </div>
            </el-form-item>
          </template>
          <template v-else-if="activeTab === 1">
            <el-form-item class="login-mobile" prop="mobile">
              <el-input
                v-model="loginForm.phonenumber"
                class="login-mobile-input"
                type="text"
                auto-complete="off"
                placeholder="请输入手机号"
              >
              </el-input>
              <el-select
                class="login-mobile-select"
                v-model="mobileCode"
                placeholder="请选择"
              >
                <el-option label="+86" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="login-smscode" prop="smscode">
              <el-input
                v-model="loginForm.phonecode"
                class="login-smscode-input"
                auto-complete="off"
                placeholder="请输入验证码"
                maxlength="6"
              >
              </el-input>
              <el-button
                class="login-smscode-text"
                type="text"
                :loading="codeLoading"
                :disabled="codeDisable"
                @click="handleGetCode"
              >
                {{ codeText }}
              </el-button>
            </el-form-item>
          </template>
          <!-- <el-checkbox
            v-model="loginForm.rememberMe"
            style="margin: 0px 0px 25px 0px"
            >记住密码</el-checkbox
          > -->
          <el-form-item :style="{ marginBottom: activeTab === 0 ? '0px' : '' }">
            <el-button
              :loading="loading"
              class="login-btn"
              size="medium"
              type="primary"
              style="width: 100%"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
<!--            <div class="login-operation">-->
<!--              <div v-if="register">-->
<!--                <el-button type="text" @click="handleToPath('/register')"-->
<!--                  >立即注册</el-button-->
<!--                >-->
<!--              </div>-->
<!--              <div v-if="forget">-->
<!--                <el-button type="text" @click="handleToPath('/forget')"-->
<!--                  >忘记密码？</el-button-->
<!--                >-->
<!--              </div>-->
<!--            </div>-->
          </el-form-item>
        </el-form>
<!--        <div class="login-type">-->
<!--          <el-divider>其他登录方式</el-divider>-->
<!--          <div class="login-type__btn">-->
<!--            <svg-icon-->
<!--              class="login-type__icon login-type__wechat"-->
<!--              icon-class="icon-wechat"-->
<!--              @click="changeLoginType(true)"-->
<!--            />-->
<!--            <svg-icon-->
<!--              class="login-type__icon login-type__iphone"-->
<!--              icon-class="icon-iphone"-->
<!--              @click="changeLoginType(false)"-->
<!--            />-->
<!--          </div>-->
<!--        </div>-->
      </div>
    </div>
    <!--  底部  -->
    <div class="login-footer">
      <span
        >Copyright © 2020-2022</span
      >
    </div>
  </div>
</template>

<script>
import { getSmsCode, getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { mapState } from 'vuex'
import { validateMobile } from '@/utils/validate'
import { title } from '@/settings.js'

export default {
  name: "Login",
  data() {
    const phoneValidator = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else if (!validateMobile(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      title,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        mobile: '',
        phonecode: '',
        rememberMe: false
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        phonenumber: [{ validator: phoneValidator, required: true, trigger: 'blur' }],
        phonecode: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      mobileCode: '1',
      // 是否已经获取验证码
      hasGetCode: false,
      codeText: '获取验证码',
      codeLoading: false,
      interval: null,
      // 是否正在倒计时
      timing: false,// 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: true,
      forget: true,
      redirect: undefined,
      activeTab: 0,  // 0-账号登录 1-密码登录
      isWeChat: false,
      wxLogin: null
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
        if (route.query.isWeChat === '1') {
          this.isWeChat = true
        }
      },
      immediate: true
    },
    isWeChat: {
      handler(val) {
        if (val) {
          this.handleWechatLogin()
        }
      },
      immediate: true
    }
  },
  computed: {
    ...mapState({
      theme: state => state.settings.theme,
    }),
    codeDisable() {
      return !validateMobile(this.loginForm.phonenumber) || this.timing
    },
  },
  created() {
    this.getCode();
    // this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    handleTab(val) {
      this.activeTab = val
    },
    async handleGetCode() {
      if (this.codeLoading) {
        return
      }
      let valid = true
      this.$refs.loginForm.validateField(['phonenumber'], (errorMessage) => {
        if (errorMessage) {
          valid = false
        }
      })
      if (!valid) {
        return
      }
      this.codeLoading = true
      const params = {
        phonenumber: this.loginForm.phonenumber
      }
      getSmsCode(params)
        .then((res) => {
          this.$message.success(res.message)
          this.hasGetCode = true
          // this.form.sign = res.data.sign
          // this.form.expiredTime = res.data.expiredTime
          this.countDown()
        })
        .finally(() => {
          this.codeLoading = false
        })
    },
    // 倒计时
    countDown() {
      let text = 60
      this.timing = true
      this.codeText = `${text}s`
      this.interval = setInterval(() => {
        text--
        if (text > 0) {
          this.codeText = `${text}s`
        } else {
          this.timing = false
          this.codeText = '获取验证码'
          clearInterval(this.interval)
        }
      }, 1000)
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      // const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        // rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // if (this.loginForm.rememberMe) {
          //   Cookies.set("username", this.loginForm.username, { expires: 30 });
          //   Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
          //   Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          // } else {
          //   Cookies.remove("username");
          //   Cookies.remove("password");
          //   Cookies.remove('rememberMe');
          // }
          this.$store.dispatch("Login", { ...this.loginForm, type: this.activeTab }).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(() => {});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
    // 切换登录方式
    changeLoginType(isWeChat) {
      this.isWeChat = isWeChat
    },
    handleWechatLogin() {
      this.$nextTick(() => {
        console.log(window.WxLogin)
        this.wxLogin = new window.WxLogin({
          self_redirect: true,
          id: 'wechat_qrcode',
          appid: process.env.appId,
          scope: 'snsapi_login',
          redirect_uri: process.env.VUE_APP_PUBLICPATH + 'wechatPc',
          state: 'STATE',
          href: process.env.VUE_APP_PUBLICPATH + 'wechat.css'
        })
      })
    },
    // 扫码结束响应
    getPostMessage(res) {
      const that = this
      const action = res.data.action
      const info = res.data.info
      switch (action) {
        case 'getWxCode':
          that.wxlogin(info)
          break
        default:
          return
      }
    },
    // 微信登录
    wxlogin(code) {
      this.$store.dispatch('user/wxlogin', { code }).then((res) => {
        if (res && res.code !== 0) {
          // 未注册或失败
          const { data } = res
          if (!data || data === null || data === 'null') {
            this.$message.error('获取用户信息失败')
            return
          }
          if (!data.wxOpenId || data.wxOpenId === null || data.wxOpenId === 'null') {
            // 此时code重复使用 或者报错
            this.$message.error('请不要重复扫码')
            return
          }
        }
      })
    },
    handleToPath(path) {
      this.$router.push(path)
    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  // background-image: url("../assets/images/login-background.jpg");
  // background-size: cover;
  position: relative;
  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 31.25%;
    height: 100%;
    background: var(--current-color);
  }
}
.login-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  max-width: 1158px;
  margin: 0 auto;
  position: relative;
  .login-logo {
    position: absolute;
    top: 20px;
    left: 0;
    display: flex;
    display: -webkit-flex;
    align-items: center;
    color: var(--current-color);
    font-size: 20px;
    font-weight: 300;
    .login-logo__img {
      width: 46px;
      height: 46px;
      border-radius: 14px;
      background: #eee;
      margin-right: 12px;
    }
  }
}
.login-lt {
  line-height: 1;
  color: #777;
  font-size: 15px;
  &__title {
    color: #000;

    font-size: 32px;
    font-weight: 700;
  }
  &__subtit {
    margin: 36px 0 29px;
    font-size: 20px;
  }
  &__des {
    margin-bottom: 23px;
  }
  &__link {
    color: var(--current-color);
  }
}
.login-rt {
  width: 436px;
  //height: 604px;
  height: 504px;
  padding: 0px 36px;
  position: relative;
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
  .login-rt__qrcode {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 78px;
    height: 78px;
    cursor: pointer;
  }
  .login-tab {
    margin-top: 80px;
    display: flex;
    display: -webkit-flex;
    &__item {
      line-height: 30px;
      color: #000;
      font-size: 20px;
      font-weight: bold;
      margin-right: 30px;
      cursor: pointer;
      &:last-child {
        margin-right: 0;
      }
      &.active {
        color: var(--current-color);
        font-weight: normal;
        position: relative;
        &::after {
          content: '';
          position: absolute;
          bottom: -6px;
          left: 50%;
          transform: translateX(-50%);
          width: 12px;
          height: 4px;
          border-radius: 16px;
          background: var(--current-color);
        }
      }
    }
  }
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  // width: 400px;
  padding: 50px 0 8px 0;
  .el-form-item {
    margin-bottom: 24px;
  }
  .el-input,
  .el-select {
    height: 48px;
  }
  ::v-deep input {
    height: 48px;
    border-radius: 8px;
    background: #fafafa;
    box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.1) inset;
  }
  .login-btn {
    padding: 17px 20px;
    box-shadow: 0px 4px 6px 0px rgba(54, 109, 250, 0.3);
    border-radius: 25px;
  }
  // .input-icon {
  //   height: 49px;
  //   width: 14px;
  //   margin-left: 2px;
  // }
  .login-code {
    width: 33%;
    height: 48px;
    float: right;
    img {
      width: 100%;
      height: 48px;
      cursor: pointer;
      vertical-align: middle;
    }
  }
}
.login-mobile {
  position: relative;
  .login-mobile-input ::v-deep input {
    padding: 0 15px 0 60px;
  }
  .login-mobile-select {
    position: absolute;
    left: 0;
    top: 0;
    width: 60px;
    ::v-deep input {
      padding: 0 20px 0 12px;
      border: 0;
      box-shadow: none;
      background: transparent;
    }
    ::v-deep .el-input__suffix {
      right: 0;
    }
    ::v-deep .el-input__icon {
      width: 20px;
    }
  }
}
.login-smscode {
  position: relative;
  .login-smscode-input ::v-deep input {
    padding: 0 90px 0 15px;
  }

  .login-smscode-text {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
  }
}
.login-operation {
  margin-top: 24px;
  display: flex;
  display: -webkit-flex;
  justify-content: space-between;
}
.login-type {
  ::v-deep .el-divider__text {
    color: #959595;
    font-size: 10px;
  }
  .login-type__btn {
    margin-top: 32px;
    text-align: center;
    .login-type__icon {
      font-size: 38px;
      color: var(--current-color);
      cursor: pointer;
      margin-right: 16px;
      &:last-child {
        margin-right: 0;
      }
    }
    .login-type__wechat {
      padding: 7px;
      font-size: 38px;
      background-color: #04ae0f;
      border-radius: 50%;
    }
  }
}
.login-wechat {
  text-align: center;
  font-size: 16px;
  line-height: 22px;

  text-align: center;
  .login-wechat__title {
    margin-top: 50px;
    color: #04ae0f;
  }
  #wechat_qrcode {
    margin: 0 auto;
    ::v-deep iframe {
      widows: 300px !important;
      height: 350px !important;
    }
  }
  .login-wechat__tip {
    margin: 32px 0;
    color: #000;
    i,
    a {
      color: #04ae0f;
    }
    i {
      margin-right: 10px;
    }
  }
}
.login-back {
  display: inline-block;
  height: 48px;
  line-height: 48px;
  padding: 0 40px;
  color: #000;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border-radius: 32px;
  background: #fafafa;
  box-shadow: 0px 3px 5px 0px rgba(0, 0, 0, 0.1) inset;
}
.login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #b4b4b4;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
